<?php
/**
 * Created by PhpStorm.
 * User: qufan
 * Date: 2016/12/18 0018
 * Time: 17:50
 */

namespace Home\Controller;
use Common\Logic\ExcelLogic;
use Think\Upload;

/**
 * 日常安排和工作安排控制器
 * Class DailyManageController
 * @package Home\Controller
 */
class DailyManageController extends HomeController
{
    public function index(){
        $this->display();
    }


    /**
     * 值班安排导入json接口
     */
    public function import(){
        $flag = false;
        $ret = array('success' => 0, 'failed'=> 0);
        if(!empty($_FILES['file_import']['name'])){
            $upload = new Upload();
            $upload->exts = array('xls', 'xlsx');
            $upload->savePath = "temp/";
            $upload->saveRule = "time";
            $upload->subName = "";
            if (! $info = $upload->upload ( $_FILES )) {
                $this->error ( $upload->getError () );
            } else { // 上传成功 获叏上传文件信息
                $resurl = $upload->rootPath . $info ['file_import'] ['savepath'] . $info ['file_import'] ['savename'];
                $excelData = ExcelLogic::read($resurl);

                $ret = ExcelLogic::importDuty($excelData,$this->orgcode);
                if (file_exists ( $resurl )) {
                    unlink ( $resurl );
                }
                $flag = true;
            }
        }
        if ($flag) {
            logOperation('值班安排','导入资料');
            $this->sucessJson($ret);
        } else {
            $this->errorJson( '导入失败' );
        }
    }

    /**
     * 值班安排列表json接口
     * @param int $limit
     * @param int $offset
     * @param null $search
     * @param int $searchSelect
     */
    public function arrangeList($limit = 10 , $offset = 0, $search = null, $searchSelect = 0){
        if(!empty($this->uids)){
            $map['_string'] = "orgcode in(".implode(',', $this->codes).")";
        }
        $map['state'] = 1;
        $records = D('DutyArrange')->where($map)->limit($offset, $limit)->group('duty_date')->order('duty_date desc')->select();
        $sql = M()->getLastSql();
        $dateArr = array_column($records, 'duty_date');
        if(!empty($this->uids)){
            $ret = D('DutyArrange')->query('select count(*) as count from (SELECT COUNT(*) AS tp_count FROM `duty_arrange` WHERE `state` = 1 AND orgcode in('.implode(',', $this->codes).') GROUP BY duty_date ) a');
        }else{
            $ret = D('DutyArrange')->query('select count(*) as count from (SELECT COUNT(*) AS tp_count FROM `duty_arrange` WHERE `state` = 1 GROUP BY duty_date ) a');
        }
        
//        $total_count = D('DutyArrange')->group('duty_date')->having('state=1')->order('duty_date desc')->count();
        $total_count = $ret[0]['count'];
        $sql2 = M()->getLastSql();
        if(!empty($this->uids)){
            $where['_string'] = "da.orgcode in(".implode(',', $this->codes).")";
        }
        $where['da.duty_date'] = array('in', $dateArr);
        $where['da.state'] = 1;
        $order['da.duty_date'] = 'desc';
        $order['dc.sort_num'] = 'asc';
        $field = 'da.duty_arrange_id, da.duty_type_id, da.duty_user, da.duty_date, da.state, dc.duty_type_code, dc.duty_type_name, dc.holidaytypeid';
        $items = D('DutyArrange')->alias('da')->join('duty_class dc on da.duty_type_id = dc.duty_type_id')->field($field)->where($where)->order($order)->select();
        $arrayData = array();
        foreach ($items as $item){
            if (!isset($arrayData[$item['duty_date']])){
                $arrayData[$item['duty_date']] = array();
            }
            $arrayData[$item['duty_date']][] = $item;
        }
        foreach ($records as &$r ){
            $r['weekday'] = get_week($r['duty_date']);
            $r['items'] = $arrayData[$r['duty_date']];
            $r['isHoliday'] = $arrayData[$r['duty_date']][0]['holidaytypeid'] == 0?0:1;
        }
        empty($total_count) && $total_count = 0;
        $result['rows'] = $records;
        $result['total'] = $total_count;
        $this->ajaxReturn($result);
    }

    /**
     * 日常工作json接口
     * @param int $limit
     * @param int $offset
     * @param null $search
     * add 添加一个时间上下排序
     */
    public function workList($limit = 10, $offset = 0, $search = null,$rder = 'desc'){
        if(!empty($this->uids)){
            $map['_string'] = "orgcode in(".implode(',', $this->codes).")";
        }
        $map['state'] = 1;
        $model = D('WorkArrange');
        $records = $model->where($map)->limit($offset, $limit)->order('send_time '.$rder)->select();
        $total_count = $model->where($map)->count();
        empty($total_count) && $total_count = 0;
        $result['rows'] = $records;
        $result['total'] = $total_count;
        $this->ajaxReturn($result);

    }

    /**
     * 添加日常工作json接口
     */
    public function addWorkArrange(){
        $data['orgcode'] = $this->orgcode;
        $data['content'] = $_POST['content'];
        $data['send_time'] = time_format(NOW_TIME);
        $data['state'] = 1;
        $model = D('WorkArrange');
        if($model->create($data)){
            $id= $model->add();
            if($id>0){
                logOperation('日常安排','新增日常安排');
                $this->sucessJson();
            }
        }
        $this->errorJson('添加失败');
    }
    /**
     * add : 修改值班安排json接口
     * user: 边个懂
     * time: 20170522
     */
    public function pudateContent(){
        if (IS_POST && is_numeric($_POST['work_arrange_id'])) {
            $model = D('WorkArrange');
            $data = array('content'=>$_POST['content'],'send_time'=>date("Y-m-d"));
            $result = $model->where("work_arrange_id=".$_POST['work_arrange_id'])->setField($data);
            if ($result) {
                logOperation('值班安排','修改值班内容');
                $this->sucessJson();
            }
        }
        $this->sucessJson('修改失败');
        
    }
    /**
     * 删除值班安排json接口
     */
    public function delArrange(){
        $ids = I('selectedIds');
        $where['duty_date'] = array('in', $ids);
        $model = D('DutyArrange');
        $records = $model->where($where)->select();
        $codes = array_column($records, 'duty_type_id');

        $res = $model->where($where)->setField('state', 0);
        $modelClass = D('DutyClass');
        $map['duty_type_id'] = array('IN', $codes);
        $modelClass->where($map)->setField('state', 0);
        if($res !== false){
            logOperation('值班安排','删除值班');
            $this->sucessJson();
        }else{
            $this->errorJson('删除失败');
        }
    }

    /**
     * 删除日常工作接口
     */
    public function delWork(){
        $ids = I('selectedIds');
        $where['work_arrange_id'] = array('in', $ids);
        $model = D('WorkArrange');
        $res = $model->where($where)->setField('state', 0);
        if($res !== false){
            logOperation('工作安排','删除工作');
            $this->sucessJson();
        }else{
            $this->errorJson('删除失败');
        }
    }


}